package com.ledi.guns.modular.ledipay.service.impl;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ledi.guns.common.exception.AppCheckException;
import com.ledi.guns.common.persistence.dao.RoleMapper;
import com.ledi.guns.common.persistence.dao.UserMapper;
import com.ledi.guns.common.persistence.model.Role;
import com.ledi.guns.common.persistence.model.User;
import com.ledi.guns.common.util.StringUtil;
import com.ledi.guns.core.redis.KeyValueDAO;
import com.ledi.guns.core.shiro.ShiroKit;
import com.ledi.guns.core.shiro.ShiroUser;
import com.ledi.guns.core.util.SystemConstans;
import com.ledi.guns.modular.ledipay.controller.req.staff.AddStaffInfo;

@Service
@Transactional(rollbackFor = Exception.class)
public class StaffServiceImpl extends ServiceImpl<UserMapper, User> {

	@Resource
	private UserMapper userMapper;

	@Resource
	private RoleMapper roleMapper;

	@Autowired
	private KeyValueDAO keyValueDAO;

	@Transactional
	public void addStaffInfo(AddStaffInfo addStaffInfo) {

		ShiroUser currentUser = ShiroKit.getUser();
		Integer creatorId = currentUser.getId();

		// 校验密码是否包含中文字符
		String staffPasswd = addStaffInfo.getPassword();
		for (int i = 0; i < staffPasswd.length(); i++) {
			if (StringUtil.isChinese(staffPasswd.charAt(i))) {
				throw new AppCheckException("agent.passwdContainChinese.code", "agent.passwdContainChinese.message");
			}
		}
		// 校验当前用户是否被删除
		User oneUser = userMapper.selectById(creatorId);
		if (1 != oneUser.getStatus()) {
			throw new AppCheckException("staff.staffUserHaveDelete.code", "staff.staffUserHaveDelete.message");
		}

		Role roleMap = new Role();
		roleMap.setName(addStaffInfo.getRoleName());
		Role roleByMap = roleMapper.selectOne(roleMap);
		if (null == roleByMap) {
			throw new AppCheckException("staff.roleNotExistError.code", "staff.roleNotExistError.message");
		}
		int roleId = roleByMap.getId();
		Map<String, Object> map = new HashMap<>();
		map.put("account", addStaffInfo.getAccount());
		List<User> staffUserList = userMapper.selectByMap(map);
		if (null != staffUserList && staffUserList.size() > 0) {
			staffUserList.forEach(staffUser -> {
				if (1 == staffUser.getStatus()) {
					if (addStaffInfo.getAccount().equals(staffUser.getAccount())) {
						String staffRoleIds = staffUser.getRoleid();
						List<String> staffRoleIdList = Arrays.asList(staffRoleIds.split(","));
						staffRoleIdList.forEach(staffRoleid -> {
							// 校验角色（老师）
								int tRoleId = roleMapper.getIdByName(SystemConstans.T_ROLENAME);
								if (String.valueOf(tRoleId).equals(staffRoleid)) {
									throw new AppCheckException("staff.staffUserExistError.code",
											"staff.staffUserExistError.message");
								}
								// 校验角色（园长）
								int kRoleId = roleMapper.getIdByName(SystemConstans.K_ROLENAME);
								if (String.valueOf(kRoleId).equals(staffRoleid)) {
									throw new AppCheckException("staff.staffUserExistError.code",
											"staff.staffUserExistError.message");
								}
								// 校验角色（代理商管理员）
								int aRoleId = roleMapper.getIdByName(SystemConstans.A_ROLENAME);
								if (String.valueOf(aRoleId).equals(staffRoleid)) {
									throw new AppCheckException("staff.staffUserExistError.code",
											"staff.staffUserExistError.message");
								}
								// 校验角色（代理商员工）
								int agentUserId = roleMapper.getIdByName(SystemConstans.AU_ROLENAME);
								if (String.valueOf(agentUserId).equals(staffRoleid)) {
									throw new AppCheckException("staff.userHaveExistError.code",
											"staff.userHaveExistError.message");
								}
								// 校验角色（员工管理员）--员工角色不与其他角色共角色
								int pRoleId = roleMapper.getIdByName(SystemConstans.P_ROLNAME);
								if (String.valueOf(pRoleId).equals(staffRoleid)) {
									throw new AppCheckException("staff.userHaveExistError.code",
											"staff.userHaveExistError.message");
								}

								// 校验角色（普通员工 ）
								int sRoleId = roleMapper.getIdByName(SystemConstans.S_ROLNAME);
								if (String.valueOf(sRoleId).equals(staffRoleid)) {
									throw new AppCheckException("staff.userHaveExistError.code",
											"staff.userHaveExistError.message");
								}

							});
					}
				} else {
					staffUser.setStatus(1);
					staffUser.setSalt(ShiroKit.getRandomSalt(5));
					staffUser.setPassword(ShiroKit.md5(addStaffInfo.getPassword(), staffUser.getSalt()));
					staffUser.setAccount(addStaffInfo.getAccount());
					staffUser.setCreatetime(new Date());
					staffUser.setCreateid(creatorId);
					staffUser.setName(addStaffInfo.getName());
					staffUser.setPhone(addStaffInfo.getAccount());
					staffUser.setComment(addStaffInfo.getComment());
					staffUser.setDeptid(SystemConstans.DEPT_STAFF_INT);
					staffUser.setRoleid(String.valueOf(roleId));
					Integer pUserUpdate = userMapper.updateById(staffUser);
					if (pUserUpdate < 1) {
						throw new AppCheckException("staff.addUserError.code",
								"staff.addUserError.message");
					}
				}
			});
		} else {
			User user = new User();
			user.setCreateid(creatorId);
			user.setAccount(addStaffInfo.getAccount());
			user.setSalt(ShiroKit.getRandomSalt(5));
			user.setPassword(ShiroKit.md5(addStaffInfo.getPassword(), user.getSalt()));
			user.setCreatetime(new Date());
			user.setRoleid(String.valueOf(roleId));
			user.setName(addStaffInfo.getName());
			user.setStatus(1);
			user.setDeptid(SystemConstans.DEPT_STAFF_INT);
			user.setPhone(addStaffInfo.getAccount());
			user.setComment(addStaffInfo.getComment());
			Integer insertUser = userMapper.insert(user);
			if (insertUser < 1) {
				throw new AppCheckException("staff.addUserError.code", "staff.addUserError.message");
			}
		}
	}

	/**
	 * 方法描述: [编辑员工.]<br/>
	 * 初始作者: 钟小平<br/>
	 * 员工没有多角色
	 * 创建日期: 2018年9月12日-上午11:58:04<br/>
	 * 开始版本: 2.0.0<br/>
	 * =================================================<br/>
	 * 修改记录：<br/>
	 * 修改作者 日期 修改内容<br/>
	 * ================================================<br/>
	 * 
	 * @param addStaffInfo
	 *            void
	 */
	@Transactional
	public void editStaffInfo(AddStaffInfo addStaffInfo) {

		ShiroUser currentUser = ShiroKit.getUser();
		Integer creatorId = currentUser.getId();

		// 校验当前用户是否被删除
		User oneUser = userMapper.selectById(creatorId);
		if (1 != oneUser.getStatus()) {
			throw new AppCheckException("school.user.notActive.code", "school.user.notActive.message");
		}
		if (addStaffInfo.getId().equals(creatorId)) {
			throw new AppCheckException("staff.currentUser.code", "staff.currentUser.message");
		}
		Role roleMap = new Role();
		roleMap.setName(addStaffInfo.getRoleName());
		Role role = roleMapper.selectOne(roleMap);
		if (null == role) {
			throw new AppCheckException("staff.roleNotExistError.code", "staff.roleNotExistError.message");
		}
		oneUser.setName(addStaffInfo.getName());
		oneUser.setVersion(addStaffInfo.getVersion());
		oneUser.setRoleid(role.getId() + "");
		oneUser.setComment(addStaffInfo.getComment());
		userMapper.updateById(oneUser);

	}

	/**
	 * 方法描述: [删除员工用户.]<br/>
	 * 初始作者: 钟小平<br/>
	 * 创建日期: 2018年10月9日-下午3:27:59<br/>
	 * 开始版本: 2.0.0<br/>
	 * =================================================<br/>
	 * 修改记录：<br/>
	 * 修改作者 日期 修改内容<br/>
	 * ================================================<br/>
	 * 
	 * @param id
	 *            void
	 */
	@Transactional
	public void deleteStaff(Integer id) {

		ShiroUser currentUser = ShiroKit.getUser();
		Integer creatorId = currentUser.getId();

		// 校验当前用户是否被删除
		User oneUser = userMapper.selectById(id);
		if (1 != oneUser.getStatus()) {
			throw new AppCheckException("school.user.notActive.code", "school.user.notActive.message");
		}
		if (id.equals(creatorId)) {
			throw new AppCheckException("staff.currentUser.code", "staff.currentUser.message");
		}
		if (oneUser.getRoleid().indexOf(SystemConstans.STAFF_ROLE_ID) == -1 || oneUser.getAccount().equals(SystemConstans.STAFF_ROLE_ADMIN)) {
			throw new AppCheckException("staff.currentUser.code", "staff.currentUser.message");
		}
		oneUser.setVersion(oneUser.getVersion());
		oneUser.setStatus(SystemConstans.THREE);
		userMapper.updateById(oneUser);

		// 删除账号重新登录
		String account = oneUser.getAccount();
		String key = SystemConstans.USER_SESSION_CHANGE.replaceAll("\\{0\\}", account);
		keyValueDAO.set(key, SystemConstans.USER_ACOUNT_STATUS_1, 0L);
	}

}
